package com.bz.match;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
 * Created on 2021/3/9
 *
 * @author zhongyongbin
 */
@Component
public class MatchMessageSubscriber implements MessageListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(MatchMessageSubscriber.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MatchManager matchManager;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String body = new String(message.getBody());
            MatchMessage matchMessage = objectMapper.readValue(body, MatchMessage.class);
            matchManager.match(matchMessage.getGameId(), matchMessage.getPlayerCount());
        } catch (JsonProcessingException e) {
            LOGGER.error("Consume match message fail.", e);
        }
    }
}
